//
//  TYHAccountLoginController.m
//  OpenPractice
//
//  Created by tanyuehong on 7/7/18.
//  Copyright © 2018年  lijinghua. All rights reserved.
//

#import "TYHAccountLoginController.h"
#import "TYHButton.h"
#import "UIView+GaussianBlur.h"
#import "CHRTextFieldFormatter.h"
#import "CHRPhoneNumberMask.h"
#import "UIDevice+Info.h"
#import "UIButton+backgroundColorForState.h"
#import "TYHHTTPFacade.h"

#define  USERPHONELENGTH  13

@interface TYHAccountLoginController ()

@property (nonatomic, strong) UIButton *arrowBtn;          //点击箭头登录
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UITextField *passField;
@property (nonatomic, strong) UILabel *placeholderLabel;
@property (nonatomic, strong) UILabel *passholderLabel;
@property (nonatomic, strong) UIView *alertView;

@property (nonatomic, strong) CHRTextFieldFormatter *phoneNumberFormatter;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicatorView;

@end

@implementation TYHAccountLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor colorWithHex:0xffffff]];
  //  [self setNavgationBarHidden:NO animated:YES];
    [self setDefaultBackItemWithBackArrow];
    [self initViews];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledTextChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_textField.text.length==USERPHONELENGTH) {
        _arrowBtn.hidden=NO;
    }
}

- (void)textFiledTextChange:(NSNotification *)no {
    UITextField *textFile = no.object;
    if (self.textField == textFile) {
        self.placeholderLabel.hidden = self.textField.text.length>0;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.textField becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [_textField resignFirstResponder];
    if (_textField.text.length == USERPHONELENGTH) {
        _arrowBtn.hidden = NO;
    }
    [super viewWillDisappear:animated];
}

#pragma mark - Private

- (void)setButtonEnable:(BOOL)enable {
    self.arrowBtn.enabled = enable;
    self.arrowBtn.backgroundColor = enable ? kThemeGreenColor : [UIColor colorWithHex:0x4cc760 andAlpha:0.5];
}

// 登录退出后 再次登录自动填写手机号
//- (void)autoFillIniPhoneNumber {
//    if ([[self getIphoneNumber] length] > 1) {
//        _textField.text = [self getIphoneNumber];
//        _placeholderLabel.hidden = YES;
//        if([self getIphoneNumber].length == USERPHONELENGTH) {
//            [self setButtonEnable:YES];
//        }
//    }
//}

// 分割字符串
//- (NSString *)getIphoneNumber {
//    NBLoginEntity * currentEntity = [NBLoginEntity read];
//    NSString *userPhone = currentEntity.phoneNumber;
//    if (userPhone.length == 11) {
//        NSString *phoneStr = [NSString stringWithFormat:@"%@ %@ %@",[userPhone substringWithRangeSafely:NSMakeRange(0, 3)],
//                              [userPhone substringWithRangeSafely:NSMakeRange(3, 4)],
//                              [userPhone substringWithRangeSafely:NSMakeRange(7, 4)]];
//        return phoneStr;
//    }
//    return  nil;
//}

- (void)setDefaultBackItemWithBackArrow {
   // [self.viewControllerHelper setDefaultBackItemWithImage:[UIImage imageNamed:@"basenav_bar_back.png"] selectedImage:[UIImage imageNamed:@"basenav_bar_back_pressed.png"]];
}

- (void)setUpSubViews {
    UIImageView *girlIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"register_girlIcon.png"]];
    girlIcon.size = CGSizeMake(110, 140);
    girlIcon.center = CGPointMake(self.view.center.x, 70);
}

- (void)initViews {
    UILabel *guideLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, kScreenHeight == 480 ? 15:88, kScreenWidth - 80, 26)];
    guideLabel.font = [UIFont systemFontOfSize:26];
    guideLabel.textColor = [UIColor colorWithHex:0x333333];
    guideLabel.text = @"请输入手机号";
    [self.view addSubview:guideLabel];
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(40, guideLabel.bottom + 39, kScreenWidth - 80, 26)];
    self.textField.font = [UIFont systemFontOfSize:26];
    self.textField.keyboardType = UIKeyboardTypeNumberPad;
    self.textField.textColor = kThemeGreenColor;
    self.textField.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:self.textField];
    
    self.placeholderLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, guideLabel.bottom + 39, kScreenWidth - 80, 26)];
    self.placeholderLabel.center = self.textField.center;
    self.placeholderLabel.font = [UIFont systemFontOfSize:26];
    self.placeholderLabel.textColor = [UIColor colorWithHex:0xd2d2d2];
    self.placeholderLabel.text = @"手机号";
    [self.view addSubview:self.placeholderLabel];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(40, self.textField.bottom + 15, kScreenWidth - 80, 0.5)];
    lineView.backgroundColor = [UIColor colorWithHex:0xe5e5e5];
    [self.view addSubview:lineView];
    
    self.passField = [[UITextField alloc] initWithFrame:CGRectMake(40, lineView.bottom + 34, kScreenWidth - 80, 22)];
    self.passField.font = [UIFont systemFontOfSize:22];
    self.passField.keyboardType = UIKeyboardTypeNumberPad;
    self.passField.textColor = kThemeGreenColor;
    self.passField.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:self.passField];
    
    self.passholderLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, lineView.bottom + 34, kScreenWidth - 80, 22)];
    self.passholderLabel.center = self.passField.center;
    self.passholderLabel.font = [UIFont systemFontOfSize:22];
    self.passholderLabel.textColor = [UIColor colorWithHex:0xd2d2d2];
    self.passholderLabel.text = @"密码";
    [self.view addSubview:self.passholderLabel];
    
    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(40, self.passField.bottom + 15, kScreenWidth - 80, 0.5)];
    lineView1.backgroundColor = [UIColor colorWithHex:0xe5e5e5];
    [self.view addSubview:lineView1];
    
    
    self.phoneNumberFormatter = [[CHRTextFieldFormatter alloc] initWithTextField:self.textField mask:[CHRPhoneNumberMask new]];
    self.arrowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.arrowBtn.frame = CGRectMake(40, lineView1.bottom + 30, kScreenWidth - 80, 40);
    [self.arrowBtn setTitle:@"登录" forState:UIControlStateNormal];
    self.arrowBtn.titleLabel.textColor = [UIColor whiteColor];
    self.arrowBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    self.arrowBtn.layer.cornerRadius = 5.f;
    [self setButtonEnable:YES];
    [self.view addSubview:_arrowBtn];
    [self.arrowBtn addTarget:self action:@selector(startLogin) forControlEvents:UIControlEventTouchUpInside];
}

- (void)startLogin {
    NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
    [dataDict setValue:@"18910647971" forKey:@"email"];
    [dataDict setValue:@"123456" forKey:@"password"];
}


//- (void)checkPhoneStatusEndWithError:(NSError *)error result:(id)result {
//    if (error) {
//        [self setButtonEnable:YES];
//        if (error.code == 99) { //帐号被踢
//            [self.view endEditing:YES];
//        }
//    } else {
//        if (result && [result isKindOfClass:[ZDSessionSubmitCheckphonestatus class]]) {
////            ZDSessionSubmitCheckphonestatus *status = (ZDSessionSubmitCheckphonestatus *)result;
////            // 使用验证码登录
////            self.showEntry = [status showEntry];
////            if ([status loginType] == 1) {
////                if ([LoginManager sharedInstance].verifyCodeCountdown != 0 && [[LoginManager sharedInstance].phoneNumberCountdown isEqualToString:[self getUserPhone]]) {
////                    SMSCodeVerifyViewController *viewController = [[SMSCodeVerifyViewController alloc] init];
////                    viewController.showEntry = [status showEntry];
////                    viewController.phoneNum = [self getUserPhone];
////                    viewController.type = REGISTERTYPE;
////                    [self.navigationController pushViewController:viewController animated:YES];
////                } else {
////                    [self.view.window addSubview:self.alertView];
////                }
//            } else if ([status loginType] == 2) {
//                PassWdVerifyViewController *viewController = [[PassWdVerifyViewController alloc] init];
//                viewController.phoneNum = [self getUserPhone];
//                [self.navigationController pushViewController:viewController animated:YES];
//            } else if ([status loginType] == 3) {
//                [[LoginManager sharedInstance] setNeedResetPasswrd:@"yes"];
//                [[LoginManager sharedInstance] saveLoginEntity];
//                SMSCodeVerifyViewController *viewController = [[SMSCodeVerifyViewController alloc] init];
//                //                    viewController.showEntry = [status showEntry];
//                viewController.showEntry = 0;
//                viewController.phoneNum = [self getUserPhone];
//                viewController.type = CodeLoginType;
//                [self.navigationController pushViewController:viewController animated:YES];
//            } else {
//                [self showMessageOnlyTip:NSLocalizedString(@"Http_Error_Tip_Server_Busy", nil) withTipType:VCShowTipTypeNetError];
//            }
//        } else {
//            [self showMessageOnlyTip:NSLocalizedString(@"Http_Error_Tip_Server_Busy", nil) withTipType:VCShowTipTypeNetError];
//        }
//        [self setButtonEnable:YES];
//    }
//}

#pragma mark - Actions

- (void)setIsLoading:(BOOL)isLoading {
    if (isLoading) {
        _activityIndicatorView.hidden = NO;
        [_activityIndicatorView startAnimating];
        //        _arrowBtn.hidden = YES;
    } else {
        [_activityIndicatorView stopAnimating];
        _activityIndicatorView.hidden = YES;
        _arrowBtn.hidden = NO;
    }
}

// 获取正常格式的用户手机号
- (NSString *)getUserPhone {
    NSArray *phoneArr = [_textField.text componentsSeparatedByString:@" "];
    NSString *str = [NSString stringWithFormat:@"%@%@%@",[phoneArr objectAtIndex:0],[phoneArr objectAtIndex:1],[phoneArr objectAtIndex:2]];
    return str;
}

- (void)backButtonTouched {
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIView *)alertView {
    if (!_alertView) {
        _alertView = [UIView GaussianBlurViewWithDark:YES];
        NSArray *alertNib = [[NSBundle mainBundle] loadNibNamed:@"sendCodeAlertView" owner:self options:nil];
        UIView *alert = [alertNib objectAtIndex:0];
        alert.tag = 50;
        CGFloat alertWidth = kScreenWidth-(DeviceIsPad?200:([UIDevice isIPhone6Plus]?100:30));
        alert.frame = CGRectMake(0, 0, alertWidth, 201);
        alert.layer.masksToBounds = YES;
        alert.layer.cornerRadius = 10;
        UIButton *cancel = (UIButton *)[alert viewWithTag:100];
        
        UIButton *ok = (UIButton *)[alert viewWithTag:200];
        UILabel *decLabel = (UILabel *)[alert viewWithTag:400];
        
        cancel.layer.cornerRadius = 5;
        cancel.layer.masksToBounds = YES;
        ok.layer.cornerRadius = 5;
        ok.layer.masksToBounds = YES;
        cancel.layer.borderWidth = 1 / [UIScreen mainScreen].scale;
        cancel.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        ok.layer.borderWidth = 1 / [UIScreen mainScreen].scale;
        ok.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        
        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:decLabel.text];
        [attr setAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHex:0x999999]} range:NSMakeRange(0, decLabel.text.length)];
        [attr setAttributes:@{NSForegroundColorAttributeName:kThemeGreenColor} range:NSMakeRange(5, 5)];
        
        [cancel setBackgroundColor:[UIColor whiteColor]  forState:UIControlStateNormal];
        [cancel setBackgroundColor:[UIColor colorWithHex:0xbbbbbb]  forState:UIControlStateHighlighted];
        [ok setBackgroundColor:kThemeGreenColor forState:UIControlStateNormal];
        [ok setBackgroundColor:kThemeGreenTranslucentColor  forState:UIControlStateHighlighted];
        
        [_alertView addSubview:alert];
        alert.center = _alertView.center;
    }
    UIView *alert = (UIView *)[_alertView viewWithTag:50];
    UILabel *phoneNum = (UILabel *)[alert viewWithTag:300];
    NSMutableString *str = [NSMutableString stringWithString:self.textField.text];
    phoneNum.text = str;
    return _alertView;
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.textField) {
        return [self.phoneNumberFormatter textField:textField shouldChangeCharactersInRange:range replacementString:string];
    } else {
        return YES;
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
